package com.wurd.test.controller;

import com.wurd.test.config.Config;
import com.wurd.test.exception.WxException;
import com.wurd.test.wx.token.AuthToken;
import com.wurd.test.wx.token.Cache;
import com.wurd.test.wx.token.Token;
import com.wurd.test.wx.token.TokenBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/wx")
public class WxController {

    @Autowired
    private Cache cache;

    @Autowired
    private TokenBuilder tokenBuilder;

    /**
     * 二维码
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/authQr")
    public String getAuthUrl(HttpServletRequest request) {
        System.out.println("authQr");
        try {
            Token preAuthCode = tokenBuilder.buildPreAuthCode();
            String redirect = request.getParameter("redirect");
            redirect = redirect == null ?
                    URLEncoder.encode(Config.redirectUrl, Charset.defaultCharset().name())
                    : redirect;
            String url = MessageFormat.format(Config.authURL, preAuthCode.getToken(), redirect);
            String redirectHtml =
                    "<html>"
                            + "<body>"
                            + "<script>"
                            + "window.location.href='" + url + "';"
                            + "</script>"
                            + "</body>"
                            + "</html>";
            return redirectHtml;
        } catch (WxException e) {
            e.printStackTrace();
            return e.getMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 扫码确认后，跳转
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/redirect")
    public Object authRedirect(HttpServletRequest request) {
        System.out.println("redirect");
        try {
            String authCode = request.getParameter("auth_code");
            String expiresIn = request.getParameter("expires_in");
            AuthToken token = tokenBuilder.buildAuthAccessToken(authCode);
            return token;
        } catch (WxException e) {
            e.printStackTrace();
            return e.getMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "error";
    }

    /**
     * 手动刷新ComponentAccessToken
     *
     * @return
     */
    @GetMapping(value = "/componentToken/refresh")
    public Object refreshComponentToken() {
        System.out.println("componentToken");
        try {
            tokenBuilder.buildComponentAccessToken(tokenBuilder.buildComponentAccessTokenBody());
        } catch (WxException e) {
            e.printStackTrace();
            return e.getMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cache.getComponentAccessToken();
    }

    @GetMapping(value = "/verifyTicket")
    public Token getComponentAccessToken() {
        System.out.println("verifyTicket");
        return cache.getVerifyTicket();
    }

    @GetMapping(value = "/componentToken")
    public Token getComponentToken() {
        System.out.println("componentToken");
        return cache.getComponentAccessToken();
    }

    @GetMapping(value = "/getAuthTokens")
    public ConcurrentHashMap<String, AuthToken> getAppIds(HttpServletRequest request) {
        System.out.println("getAuthTokens");
        return cache.getAppAuthRefreshToken();
    }

}
